#!/usr/bin/perl
# file tcp_echo_chi2.pl
use strict;
use IO::Socket;
my ($bytes_out, $bytes_in) = (0,0);

my $host = shift || 'localhost';
my $port = shift || 'echo';

my $socket = IO::Socket::INET->new("$host:$port") or die $@;
# $socket->autoflush(1);
# 不需要autoflush，IO::Socket从1.18开始默认打开autoflush模式

while(defined(my $msg_out = STDIN->getline)){
    print $socket $msg_out;
    my $msg_in = <$socket>;
    print $msg_in;

    $bytes_out += length($msg_out);
    $bytes_in += length($msg_in);
}

$socket->close or warn $@;
print STDERR "bytes sent = $bytes_out, byte received = $bytes_in\n";
